#include "manager.h"

namespace Base {

template<class Item>
Manager<Item>::Manager() :
    m_mutex(QMutex::Recursive)
{
}

//-------------------------------------------------------------------------------------
template<class Item>
Manager<Item>::~Manager()
{
}

//-------------------------------------------------------------------------------------
template<class Item>
Item *Manager<Item>::byIndex(int index)
{
    QMutexLocker locker(&m_mutex);

    if (index < 0 || index >= count())
        return NULL;

    return m_itemList.at(index);
}

//-------------------------------------------------------------------------------------
template<class Item>
Item *Manager<Item>::byId(qint64 id)
{
    QMutexLocker locker(&m_mutex);

    ItemFinderIterator iterator = m_itemFinder.find(id);
    if (iterator == m_itemFinder.end())
        return NULL;

    return *iterator;
}

//-------------------------------------------------------------------------------------
template<class Item>
int Manager<Item>::indexOf(Item *item)
{
    QMutexLocker locker(&m_mutex);

    return m_itemList.indexOf(item);
}

//-------------------------------------------------------------------------------------
template<class Item>
int Manager<Item>::count()
{
    QMutexLocker locker(&m_mutex);

    return m_itemList.count();
}

//-------------------------------------------------------------------------------------
template<class Item>
const typename Manager<Item>::ItemList &Manager<Item>::itemList()
{
    QMutexLocker locker(&m_mutex);
    return m_itemList;
}

//-------------------------------------------------------------------------------------
template<class Item>
void Manager<Item>::insertItem(int position, Item *item)
{
    QMutexLocker locker(&m_mutex);

    if (m_itemList.contains(item))
        return;

    itemAboutToBeAdded(item);

    m_itemList.insert(position, item);

    itemAdded(item);
}

//-------------------------------------------------------------------------------------
template<class Item>
void Manager<Item>::appendItem(Item *item)
{
    QMutexLocker locker(&m_mutex);

    if (m_itemList.contains(item))
        return;

    itemAboutToBeAdded(item);

    m_itemList.append(item);

    itemAdded(item);
}

//-------------------------------------------------------------------------------------
template<class Item>
void Manager<Item>::removeItem(Item *item)
{
    QMutexLocker locker(&m_mutex);

    if (!m_itemList.contains(item))
        return;

    itemAboutToBeRemoved(item);

    m_itemList.removeAll(item);

    itemRemoved(item);
}

} // namespace Base
